<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="72px"
			class="queryForms">
			<el-form-item label="计划编号" prop="planNumber">
				<el-input v-model="queryParams.planNumber" placeholder="请输入计划编号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="计划状态" prop="approvalStatus">
				<el-select v-model="queryParams.approvalStatus" placeholder="请选择">
					<el-option v-for="dict in dict.type.default_approve" :key="dict.value" :label="dict.label"
						:value="dict.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="返修单号" prop="repairNumber">
				<el-input v-model="queryParams.repairNumber" placeholder="请输入返修单号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品名称" prop="productName">
				<el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input v-model="queryParams.productModel" placeholder="请输入产品型号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品编号" prop="productNumber">
				<el-input v-model="queryParams.productNumber" placeholder="请输入产品编号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-circle-check" size="mini" @click="handleSubmits"
					v-hasPermi="['plan:production:submit']">提交</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-s-order" size="mini" @click="handleApprove"
					v-hasPermi="['plan:production:approve']">审批</el-button>
			</el-col>
			<right-toolbar @changeTableData="changeTableData" menuNames="production25" :showSearch.sync="showSearch"
				@queryTable="handleQuery" :columns.sync="columns" perm="plan:production:index"></right-toolbar>
		</el-row>
		<!--   -->
		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<el-table ref="table" @mousedown.native="mousedownTable" @row-click="row_click"
				@cell-mouse-enter="cell_mouse_enter" @cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable"
				@mouseleave.native="mouseupTable" v-loading="loading" :data="ProductionList"
				@selection-change="handleSelectionChange" row-key="id" lazy :load="loadListDes"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border height="100%"
				:row-class-name="tableRowClassName">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					           <template slot-scope="scope">
						               <div>{{ scope.row.sort }}</div>
						           </template>
					        </el-table-column>

				<el-table-column label="计划编号" prop="planNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[0].visible" />
				<el-table-column label="返修任务单" prop="repairNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[1].visible" />
				<el-table-column label="产品名称" prop="productName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[4].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[5].visible" />
				<el-table-column label="产品编号" prop="productNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[6].visible" />
				<el-table-column label="3B号" prop="bnumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[7].visible" />
				<el-table-column label="客户代表" prop="productRepresentativeName" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="用户" prop="clientName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[3].visible" />
				<el-table-column label="工艺流程" prop="technologyName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[8].visible">
					<template slot-scope="scope">
						<div @click="showTechnologyList(scope.row)">
							{{ scope.row.technologyName }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="工艺状态" prop="technologyState" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[9].visible">
					<template slot-scope="scope">
						<div :style="{ color: scope.row.technologyState === '逾期' ? 'red' : '' }">{{
							scope.row.technologyState }}</div>
					</template>
				</el-table-column>
				<el-table-column label="计划开始时间" align="center" prop="technologyBeginTime" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[10].visible" />
				<el-table-column label="计划完成时间" align="center" prop="technologyFinishTime" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[11].visible" />
				<el-table-column label="计划状态" prop="approvalStatus" min-width="150" align="center"
					:show-overflow-tooltip="true" v-if="columns[12].visible">
					<template slot-scope="scope">
						<!-- <div @click="showApproveList(scope.row)">
							<dict-tag :options="dict.type.default_approve" :value="scope.row.approvalStatus" />
						</div> -->
						<el-tag type="info" v-if="scope.row.approvalStatus === '0'" class="disableClick">未提交</el-tag>
						<el-tag v-if="scope.row.approvalStatus === '1'" @click="showApproveList(scope.row)"
							class="clickable">审批中</el-tag>
						<el-tag type="success" v-if="scope.row.approvalStatus === '2'"
							@click="showApproveList(scope.row)" class="clickable">已通过</el-tag>
						<el-tag type="danger" v-if="scope.row.approvalStatus === '3'"
							@click="showApproveList(scope.row)" class="clickable">未通过</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" class-name="small-padding fixed-width" width="220px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-circle-check"
								@click="handleSubmit(scope.row)"
								v-if="scope.row.approvalStatus == '0' || scope.row.approvalStatus == '3'"
								v-hasPermi="['plan:production:submit']">提交</el-button>
							<!-- 审批中显示 -->
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleApprove(scope.row)"
								v-if="scope.row.approvalStatus == '1' && scope.row.userApprovalStatus == '0'"
								v-hasPermi="['plan:production:approve']">审批</el-button>
							<!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDetail(scope.row)" v-hasPermi="['plan:production:detail']">详情</el-button> -->
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)"
								v-hasPermi="['plan:production:annex']">附件</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
								v-hasPermi="['plan:production:remove']"
								v-if="scope.row.approvalStatus === '0' || scope.row.approvalStatus === '3'">删除</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail2(scope.row)"
								v-hasPermi="['plan:production:detail']">详情</el-button>
							<el-button size="mini" type="text" icon="el-icon-s-operation" @click="handlePlan(scope.row)"
								v-hasPermi="['plan:production:plan']">生产计划</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination29" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 审批弹框 -->
		<el-dialog title="审批" :visible.sync="openApprove" width="900px" append-to-body v-dialogDrag>
			<ApproveTemplete @cancelApprove="cancelApprove" :openApprove="openApprove"></ApproveTemplete>
		</el-dialog>

		<!-- 生产计划框 -->
		<el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body v-dialogDrag>
			<ProductPlan ref="productplan" :form="form" :isOne="isOne" :disabled="disabled" />
			<div slot="footer" class="dialog-footer" v-if="!disabled">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 审批流程弹框 -->
		<el-dialog title="审批流程" :visible.sync="openRecords" width="900px" append-to-body v-dialogDrag>
			<RecordsTemplete :approveRecord="approveRecord"></RecordsTemplete>
		</el-dialog>
	</div>
</template>

<script>
import DocumentShow from "@/views/components/DocumentShow"
import { listProduction, listProductionChild, submitProduction, getProduction, delProduction, productionApprove, getPlanData, editProductionPlan, deletePlan } from "@/api/plan/production"
import ApproveTemplete from "@/views/components/ApproveTemplete"
import ProductPlan from "@/views/components/ProductPlan"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { approvalRecord } from "@/api/productTechnology/productTechnologyVersions"
import { mapGetters } from "vuex"
import { getcolumn } from "@/api/selectList"
import searchStateMixin from '@/layout/mixin/searchStateMixin.js'
export default {
	name: "Production",
	dicts: ["default_approve", "product_intact_state"],
	mixins: [searchStateMixin],
	components: { ApproveTemplete, ProductPlan, RecordsTemplete, DocumentShow },
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			fileVedioList: [],
			showfileListDialog: false,
			showTodoListDialog: false,
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 设备保养计划表格数据
			ProductionList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				planNumber: undefined,
				approvalStatus: undefined,
				repairNumber: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				scheduleName: [{ required: true, message: "请输入计划名称", trigger: "blur" }]
			},
			deviceList: [],
			// 更新树刷新
			treeMap: new Map(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 生产计划
			isOne: false,
			disabled: false,
			// 审批流程
			openRecords: false,
			approveRecord: [],
			treetablekey: Math.random(),
			// 列信息
			columns: [
				{ key: 0, label: `计划编号`, visible: true },
				{ key: 1, label: `返修任务单`, visible: true },
				{ key: 2, label: `客户代表`, visible: true },
				{ key: 3, label: `用户`, visible: true },
				{ key: 4, label: `产品名称`, visible: true },
				{ key: 5, label: `产品型号`, visible: true },
				{ key: 6, label: `产品编号`, visible: true },
				{ key: 7, label: `3B号`, visible: true },
				{ key: 8, label: `工艺流程`, visible: true },
				{ key: 9, label: `工艺状态`, visible: true },
				{ key: 10, label: `计划开始时间`, visible: true },
				{ key: 11, label: `计划完成时间`, visible: true },
				{ key: 12, label: `计划状态`, visible: true }
			]
		}
	},
	created() {
			// this.getSize()
		// 如果是页面刷新，重置查询
		if (window.performance && performance.navigation.type === performance.navigation.TYPE_RELOAD) {
			// 清除URL中的查询参数（不刷新页面）
			this.resetForm("queryForm")
			window.history.replaceState({}, document.title, window.location.pathname)
		}
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				if (newQuery.queryData) {
					if (Object.keys(newQuery.queryData).length === 0) {
						this.resetQuerys()
						// this.getSize()
					} else {
						this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
						// this.getSize()
					}
				} this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	activated() {
		// this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination29" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		tableRowClassName({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		/** 查询设备保养计划列表 */
		getList() {
			this.loading = true
			listProduction(this.queryParams).then(response => {
				this.ProductionList = response.rows
				this.ProductionList.forEach((item, index) => {
					item.hasChildren = true
					item.sort = index + 1
					// this.$refs.table.toggleRowExpansion(item, false);
				})
				this.total = response.total
				this.loading = false
			})
		},
		// 获取列表详情
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, {
					treeNode,
					resolve
				})
			}
			let queryParams = JSON.parse(JSON.stringify(this.queryParams))
			delete queryParams.pageSize
			delete queryParams.pageNum
			let data = {
				id: tree.id,
				...queryParams
			}
			let ret = await listProductionChild(data)
			ret.rows.forEach((item, index) => {
				// 父子id会冲突
				item.id = "c" + item.id
				item.sort = index + 1
			})
			resolve(ret.rows)
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				scheduleNumber: undefined,
				scheduleName: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.saveSearchState()
			this.getList()
			this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuerys() {
			this.resetForm("queryForm")
			this.queryParams = {
				pageNum: 1,
				pageSize: this.queryParams.pageSize,
				planNumber: undefined,
				approvalStatus: undefined,
				repairNumber: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined
			}
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.queryParams = {
				pageNum: 1,
				pageSize: this.queryParams.pageSize,
				planNumber: undefined,
				approvalStatus: undefined,
				repairNumber: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined
			},
			this.clearSearchCache()
				this.handleQuery()
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		// 单击表格行
		row_click(row, column, event) {
			// this.currentEnterRow || this.$refs.table.toggleRowSelection(row)
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		// async handleAdd() {
		//   this.reset();
		//   // 获取保养编号和设备列表
		//   let ret = await getProductionNumber();
		//   if (ret.code == 200) {
		//     this.form.scheduleNumber = ret.msg;
		//   }
		//   let res = await getProductionEquipmentList();
		//   if (res.code == 200) {
		//     this.deviceList = res.rows;
		//   }
		//   this.open = true;
		//   this.title = "制定设备保养计划";
		// },
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			const id = row.id || this.ids
			getProduction(id).then(response => {
				this.form = response.data
				this.open = true
				this.title = "修改设备保养计划"
			})
		},
		/** 提交按钮 */
		submitForm() {
			editProductionPlan(this.form).then(response => {
				this.$modal.msgSuccess("操作成功")
				this.open = false
				localStorage.setItem("todoMessage", 'production5')
				// 刷新树
				this.treeMap.forEach((item, idx) => {
					this.loadListDes({ id: idx }, item.treeNode, item.resolve)
				})
				this.$refs.table.clearSelection()
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return deletePlan(ids)
				})
				.then(() => {
					this.getList()
					this.$refs.table.clearSelection()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => { })
		},
		handleSubmits() {
			let checkp = this.rows.every(item => {
				return typeof item.id == "number"
			})
			if (!checkp) {
				this.$modal.msg("只能选择父级产品进行提交")
				return false
			}
			const _this = this
			this.$modal
				.confirm(`是否确认提交数据？`)
				.then(function () {
					return submitProduction({
						workIds: _this.ids,
						workflowType: "5"
					})
				})
				.then(() => {
					_this.getList()
					localStorage.setItem("todoMessage", 'production1')
					_this.$modal.msgSuccess("提交成功")
					_this.$refs.table.clearSelection()
				})
				.catch(() => { })
		},
		// 列表父级提交
		handleSubmit(row) {
			this.$modal
				.confirm("是否确认提交数据项？")
				.then(function () {
					let data = {
						workId: row.id,
						workflowType: "5",
						// 1是提交，3是重复提交
						submitStatus: row.approvalStatus == "0" ? "1" : "2"
					}
					return submitProduction(data)
				})
				.then(() => {
					this.getList()
					localStorage.setItem("todoMessage", 'production2')
					this.$refs.table.clearSelection()
					this.$modal.msgSuccess("操作成功")
				})
				.catch(() => { })
		},

		// 生产计划
		async handlePlan(row) {
			this.disabled = false
			let id = row.id.replace("c", "")
			let ret = await getPlanData(id)
			this.form = ret.data
			this.form.tproductTechnologyList = this.form.tproductionTechnologyPlanList || []
			this.open = true
			this.title = "修改生产计划"
			// 判断是一条还是多条
			this.isOne = this.form.repairNumber.split(",").length == 1
		},

		// 子级详情
		async handleDetail2(row) {
			this.disabled = true
			let id = row.id.replace("c", "")
			let ret = await getPlanData(id)
			this.form = ret.data
			this.form.tproductTechnologyList = this.form.tproductionTechnologyPlanList || []
			this.open = true
			this.title = "生产计划详情"
			// 判断是一条还是多条
			this.isOne = this.form.repairNumber.split(",").length == 1
		},

		// 生产详情（父级详情）
		async handleDetail(row) {
			this.disabled = true
			let ret = await getPlanData(row.id)
			this.form = ret.data
			this.form.tproductTechnologyList = this.form.tproductionTechnologyPlanList || []
			this.open = true
			this.title = "详情"
		},

		// 审批
		handleApprove(row) {
			this.approveRow = row
			if (!row.id) {
				let checkp = this.rows.every(item => {
					return typeof item.id == "number"
				})
				if (!checkp) {
					this.$modal.msg("只能选择父级产品进行审批")
					return false
				}
			}
			this.openApprove = true
		},

		// 审批取消
		async cancelApprove(ret) {
			if (!ret.flag) {
				this.openApprove = false
				return false
			}
			let data = {
				approvalStatus: ret.approvalStatus,
				causeRejection: ret.causeRejection,
				workflowType: "5"
			}
			this.approveRow.id ? (data.id = this.approveRow.id) : (data.ids = this.ids)
			let res = await productionApprove(data)
			if (res.code == 200) {
				this.$modal.msgSuccess("操作成功")
				this.getList()
				localStorage.setItem("todoMessage", 'production3')
				this.$refs.table.clearSelection()
			}
			this.openApprove = false
		},
		// 获取审批详情
		showApproveList(row) {
			if (row.approvalStatus == "0") {
				return false
			}
			this.openRecords = true
			approvalRecord({
				id: row.id,
				workflowType: "5"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		},
		// 关闭更改保养计划
		cancelChange() {
			this.changeOpen = false
		},
		// 工艺流程列表
		showTechnologyList() {
			return false
			alert("工艺流程列表")
		},
		// 附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 8,
					perm: "plan:production:annex",
					// queryParams: JSON.stringify(this.queryParams),
					paths: "/plan/production",
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 220px !important;
}
</style>
<style>
.el-table .warning-row {
	color: red;
}
</style>
